package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.vnp.cooking.adapter.ListThongbaoAdapter;
import com.vnp.cooking.bean.ObjThongbao;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.PreferenceHelper;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ThongbaoActivity extends Activity implements OnTouchListener {

	ImageButton btnBack;
	TextView titleThongbao;
	PreferenceHelper preferenceHelper;
	int mPage = 0;
	ListView listThongbao;
	ListThongbaoAdapter adapter;
	ArrayList<ObjThongbao> objThongbaos = new ArrayList<ObjThongbao>();
	ProgressBar progressBarLoading;
	TextView txtKoThongbao;
	private static final String SCREEN_LABEL = "Thong bao screen";

	// loadmore
	private int preLast;
	boolean isLoading = false;
	boolean canLoadMore = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_thongbao);

		preferenceHelper = new PreferenceHelper(this);

		btnBack = (ImageButton) findViewById(R.id.btn_back);
		titleThongbao = (TextView) findViewById(R.id.title_thongbao);
		listThongbao = (ListView) findViewById(R.id.list_thongbao);
		progressBarLoading = (ProgressBar) findViewById(R.id.progressBarLoading);
		txtKoThongbao = (TextView) findViewById(R.id.txt_ko_thongbao);

		getThongbao(mPage);

		adapter = new ListThongbaoAdapter(ThongbaoActivity.this, objThongbaos);
		listThongbao.setAdapter(adapter);

		listThongbao.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long id) {
				gotoChitietMonan(objThongbaos.get(position).getRecipeId());
			}

		});

		init();

		listThongbao.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int lastItem = firstVisibleItem + visibleItemCount;
				if (lastItem == totalItemCount) {
					if (preLast != lastItem) {
						int last_pos = listThongbao.getLastVisiblePosition();
						if (last_pos >= objThongbaos.size() - 1 && !isLoading
								&& (canLoadMore == true)) {
							progressBarLoading.setVisibility(View.VISIBLE);
							getThongbao(++mPage);
						} else {

						}
					} else {

					}
				} else {

				}
			}
		});
		
		ApplicationContext.getGaTracker().set(Fields.SCREEN_NAME, SCREEN_LABEL);

	}
	
	@Override
	public void onStart() {
		super.onStart();
		ApplicationContext.getGaTracker().send(MapBuilder.createAppView().build());
	}

	@Override
	public void onStop() {
		super.onStop();
	}

	void gotoChitietMonan(String recipeID) {
		Intent t = new Intent(ThongbaoActivity.this,
				ChitietThongbaoActivity.class);
		t.putExtra("recipe_id", recipeID);
		startActivity(t);
	}

	void init() {
		btnBack.setOnTouchListener(this);
	}

	void getThongbao(final int page) {

		isLoading = true;
		canLoadMore = false;
		HttpClientHelper httpClientHelper = new HttpClientHelper(
				new MyJsonHttpResponseHandler() {

					@Override
					public void onFailure(Throwable error) {
						super.onFailure(error);
						progressBarLoading.setVisibility(View.GONE);
						isLoading = false;
					}

					@Override
					public void onSuccess(JSONObject re) {
						super.onSuccess(re);
						progressBarLoading.setVisibility(View.GONE);
						isLoading = false;
						try {
							int status = re.getInt("status");
							if (status == 200) {
								JSONArray data = re.getJSONArray("data");
								if (page == 0) {
									if (data.length() == 0) {
										txtKoThongbao.setVisibility(View.VISIBLE);
									} else {
									}
								} else {
								}
								for (int i = 0; i < data.length(); i++) {

									JSONObject js = data.getJSONObject(i);
									ObjThongbao objThongbao = new ObjThongbao();

									JSONObject user = js
											.getJSONObject("user");
									objThongbao.setAvataChef(user
											.getString("avatar"));
									Log.i("DATA", user.getString("avatar"));
									objThongbao.setNameChef(user
											.getString("name"));
									objThongbao.setTypeThongbao(js
											.getString("action"));
									JSONObject recipe = js
											.getJSONObject("recipe");
									objThongbao.setNameRecipe(recipe
											.getString("name"));
									objThongbao.setCreated(js
											.getString("created"));
									objThongbao.setRecipeId(recipe
											.getString("id"));
									if (recipe.getString("id").equals(null)&&(recipe.getString("")).equals("")) {
										
									} else {
										objThongbaos.add(objThongbao);
									}
									
								}
								adapter.notifyDataSetChanged();
								if (data.length() == 10) {
									canLoadMore = true;
								} else {
									canLoadMore = false;
								}

							} else {
								progressBarLoading.setVisibility(View.GONE);
								Toast.makeText(ThongbaoActivity.this,
										"Không lấy được danh sách thông báo.",
										Toast.LENGTH_SHORT).show();
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});

		httpClientHelper.getNofication(preferenceHelper.getID(), page);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				closeActivity();
			}
			break;

		default:
			break;
		}
		return false;
	}

	void closeActivity() {
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}

	@Override
	public void onBackPressed() {
		closeActivity();
	}

}
